package com.tenement.netty.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.mybatisflex.core.tenant.TenantManager;
import com.tenement.entity.Chat;
import com.tenement.entity.ChatModel;
import com.tenement.entity.User;
import com.tenement.netty.service.ChatHandlerService;
import com.tenement.service.ChatService;
import com.tenement.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.BeanUtils;


import java.sql.Timestamp;
import java.util.*;

public class PrivateServiceImpl implements ChatHandlerService {

    private ChatService chatService = SpringUtil.getBean(ChatService.class);

    private UserService userService = SpringUtil.getBean(UserService.class);


    @Override
    public void execute(ChatModel chatModel, ChannelHandlerContext channelHandlerContext, Map<String, Channel> privateChannel, Set<Channel> channelGroups) {
        Channel channel = privateChannel.get(chatModel.getTarget().toString());
        List<User> users = TenantManager.withoutTenantCondition(() -> {
            ArrayList<Long> ids = new ArrayList<>();
            ids.add(chatModel.getTarget());
            ids.add(chatModel.getUserId());
            return userService.listByIds(ids);
        });
        Chat chat = new Chat();
        chatModel.setSendTime(new Timestamp(new Date().getTime())).setUsers(users);
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(chatModel)));
        }
        BeanUtils.copyProperties(chatModel,chat);
        chatService.save(chat);
    }
}
